// 检查收藏状态云函数
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()

exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const { type, itemId } = event
  
  try {
    console.log('检查收藏状态，类型:', type, '项目ID:', itemId)
    
    // 直接使用openid作为用户标识
    if (!wxContext.OPENID) {
      return {
        success: false,
        message: '用户未登录'
      }
    }
    
    const userOpenid = wxContext.OPENID

    if (!type || !itemId) {
      return {
        success: false,
        message: '参数不完整',
        error: 'MISSING_PARAMS'
      }
    }

    if (!['activity', 'goods'].includes(type)) {
      return {
        success: false,
        message: '收藏类型无效',
        error: 'INVALID_TYPE'
      }
    }

    // 查询用户收藏记录
    const collectionResult = await db.collection('user_collection')
      .where({
        userId: userOpenid
      })
      .get()

    if (collectionResult.data.length === 0) {
      // 用户还没有收藏记录
      return {
        success: true,
        data: {
          isCollected: false,
          type,
          itemId
        },
        message: '未收藏'
      }
    }

    const userCollection = collectionResult.data[0]
    const fieldName = type === 'activity' ? 'activityLikes' : 'goodsLikes'
    const currentList = userCollection[fieldName] || []
    
    const isCollected = currentList.includes(itemId)

    return {
      success: true,
      data: {
        isCollected,
        type,
        itemId
      },
      message: isCollected ? '已收藏' : '未收藏'
    }

  } catch (error) {
    console.error('检查收藏状态失败:', error)
    return {
      success: false,
      message: '检查收藏状态失败',
      error: error.message,
      details: error
    }
  }
}